import { createRouter, createWebHashHistory } from 'vue-router'
import { checkTokenValid } from '../utils/checktokenValid.js'
const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'Login',
      component: () => import('../views/LoginPage.vue'),
      meta: {
        requiresAuth: false // 明确标记不需要认证
      }
    },
    {
      path: '/image-cropping',
      name: 'image-cropping',
      component: () => import('../views/Image_cropping.vue'),
      // meta: {
      //   requiresAuth: false // 明确标记不需要认证
      // }
    },
    {
      path: '/',
      name: 'Layout',
      component: () => import('../views/LayoutContainer.vue'),
      redirect: { name: 'CommonAi' },
 
      children: [
        {
          path: 'common-ai',
          name: 'CommonAi',
          component: () => import('../views/CommonAl.vue')
        },
        {
          path: 'questionAi',
          name: 'QuestionAi',
          component: () => import('../views/QuestionAl.vue'),
               meta: {
        requiresAuth: true // 父路由标记需要认证，子路由默认继承
      },
        }
      ]
    },
    {
      path: '/personInformation',
      name: 'PersonInformation',
      component: () => import('../views/PersonInformation.vue'),
      meta: {
        requiresAuth: true // 需要认证
      }
    }
    , {
      path: '/dictCharSearch',
      component: () => import('../views/DictCharSearch.vue'),
       meta: {
        requiresAuth: true // 需要认证
      }
    }
  ]
})


router.beforeEach(async (to, from, next) => {
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
  const isAuthenticated = await checkTokenValid()

  if (requiresAuth && !isAuthenticated) {
    next({ name: 'Login'})
  } else if (to.name === 'Login' && isAuthenticated && !to.query.fromLogout) {
    // 改为检查 query.fromLogout 而不是 params.fromLogout
    next({ name: 'CommonAi' })
  } else {
    next()
  }
})
export default router